package com.lookme.lmtool.cracker;

import cn.hutool.core.annotation.AnnotationUtil;
import com.lookme.lmtool.cracker.annotation.ParamAnnotation;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractCracker implements ICracker {
    private transient long costTime;
    /**
     * @return 返回该图像对像的描述信息
     */
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        Class<?> sc = this.getClass();
        List<Field> fields = getHasParamFieldList(this);
        for (Field f : fields) {
            f.setAccessible(true);
            ParamAnnotation annotation=f.getAnnotation(ParamAnnotation.class);
            try {
                if (null != f.get(this)){
                    sb.append(annotation.name() + "=" + f.get(this) + " ");
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
            }
        }
        if(sb.length()==0){
            sb.append("-");
        }
        return sb.toString();
    }

    /**
     * 获取拥有注解的字段
     * @param cracker 图像操作对象
     * @return 返回字段列表
     */
    public static List<Field> getHasParamFieldList(ICracker cracker){
        List<Field> list=new ArrayList<>();
        Field[] fields= cracker.getClass().getDeclaredFields();
        for(Field field:fields){
            ParamAnnotation annotation= AnnotationUtil.getAnnotation(field,ParamAnnotation.class);
            if(annotation!=null){
                list.add(field);
            }
        }
        return list;
    }

    @Override
    public long getCostTime() {
        return costTime;
    }

    @Override
    public void setCostTime(long costTime) {
        this.costTime = costTime;
    }
}
